/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui_xmlparser;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 *
 * Rivera, Valencia, De Grano, Tan, Macatangay
 */
public class Interface extends javax.swing.JFrame {

    private String structure = " ";
    private boolean willPrint = true;
    private ArrayList<Constituent> ConstList = new ArrayList();
    private ArrayList<String> conceptComponents = new ArrayList();
    private ArrayList<String> labelComponents = new ArrayList();
    
    public Interface() {
        initComponents();
        Dimension dim = getToolkit().getScreenSize();
        Rectangle abounds = getBounds();
        setLocation((dim.width - abounds.width) / 2, (dim.height - abounds.height) / 2);
        fileChooser.setVisible(false);
        setTitle("Semantic Representation");
        setResizable(false);
        DefaultTableModel model = new DefaultTableModel();
        conceptsTable.setModel(model);
        model.addColumn("Concept");
        model.addColumn("Label");
        structureArea.setEditable(false);
        resultArea.setEditable(false);
    }

    public void storeToComponents(){
        for(int i=0; i<conceptsTable.getRowCount(); i++){
            conceptComponents.add(i, conceptsTable.getValueAt(i, 0).toString());
            labelComponents.add(i, conceptsTable.getValueAt(i, 1).toString());
        }
    }
    
    public void addConceptsToList(Constituent c, DefaultTableModel model){    
        if(c.getConcept()!=null){
            model.addRow(new Object[]{c.getConcept(),c.getLabel()});
            //System.out.println("COLOR~" + c.getLabel());
            //System.out.println(c.getConcept());
        }
        
        if(c.getSubconstituents()!=null){
            for(int i=0;i<c.getSubconstituents().getConstitListSize();i++){
                addConceptsToList(c.getSubconstituents().getConstList().get(i),model);
            }
        }
    }
   
    public void print(Constituent c, String paramConcept, String paramLabel){
        //System.out.println("MMMMMMMMMMMMMMMMM "+ c.getConcept() + " " + paramConcept + " " + c.getLabel()+" " + paramLabel);
        if(c.getConcept()!=null && c.getConcept().equals(paramConcept) && c.getLabel().equals(paramLabel)){
        	willPrint = false;
        }
        
        if(willPrint==true){
            if(c.getConcept()!=null && c.getLabel()!=null){
                structure = structure + c.getLabel() + ": " + c.getConcept() + "\n";
                System.out.println(c.getLabel() + ": " + c.getConcept());
            }
            
            else if(c.getConcept()==null && c.getLabel()!=null){
                structure = structure + c.getLabel() + "\n";
                System.out.println(c.getLabel());
            }
        }

        if(c.getFeatures()!= null)
        {
                for(Feature f: c.getFeatures().getFeatureList())
                {
                        f.getName();
                        f.getValue();
                        
                        if(willPrint==true){
                            structure = structure + f.getName() + ": " + f.getValue() + "\n";
                            System.out.println(f.getName() + ": " + f.getValue());
                        }
                }
        }

        if(c.getSubconstituents()!=null){
            for(Constituent sub: c.getSubconstituents().getConstList())
            {
                    print(sub, paramConcept, paramLabel);
            }
        }
        
    }
    
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        structureArea = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        conceptsTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        resultArea = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        fileChooser = new javax.swing.JFileChooser();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        openMenu = new javax.swing.JMenuItem();
        exitMenu = new javax.swing.JCheckBoxMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(null);

        jPanel2.setLayout(null);

        structureArea.setColumns(20);
        structureArea.setRows(5);
        jScrollPane4.setViewportView(structureArea);

        jPanel2.add(jScrollPane4);
        jScrollPane4.setBounds(0, 0, 330, 210);

        jScrollPane2.setViewportView(jPanel2);

        jPanel1.add(jScrollPane2);
        jScrollPane2.setBounds(390, 50, 330, 210);

        jScrollPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        conceptsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        conceptsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                conceptsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(conceptsTable);

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(20, 50, 350, 210);

        jButton1.setText("Generate!");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(600, 560, 110, 40);

        resultArea.setColumns(20);
        resultArea.setRows(5);
        jScrollPane5.setViewportView(resultArea);

        jPanel1.add(jScrollPane5);
        jScrollPane5.setBounds(20, 330, 700, 220);
        jPanel1.add(jSeparator1);
        jSeparator1.setBounds(20, 280, 690, 10);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setText("RESULT:");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(280, 290, 340, 40);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel2.setText("BASIC SEMANTIC REPRESENTATION:");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(90, 10, 630, 40);
        jPanel1.add(fileChooser);
        fileChooser.setBounds(0, 0, 731, 419);

        jMenu1.setText("File");

        openMenu.setText("Open XML file..");
        openMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuActionPerformed(evt);
            }
        });
        jMenu1.add(openMenu);

		JMenuItem saveFile = new JMenuItem("Save XML");
        saveFile.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				saveFile();
			}
		});
        jMenu1.add(saveFile);

        exitMenu.setText("Exit");
        exitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuActionPerformed(evt);
            }
        });
        jMenu1.add(exitMenu);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 741, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
        );

        pack();
    }
    
    private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {
    	fileChooser.setVisible(true);
        int returnVal = fileChooser.showOpenDialog(this);
        
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        
        System.out.println("FILE PATH: " + file.getAbsolutePath());
        
        XML xml = new XML(file.getAbsolutePath());
        SAXhandler handler = new SAXhandler();
        xml.setHandler(handler);
        
            try {
                xml.read();
                ConstList = handler.getConstList();
                DefaultTableModel model = new DefaultTableModel();
                conceptsTable.setModel(model);
                model.addColumn("Concept");
                model.addColumn("Label");
                addConceptsToList(ConstList.get(0),model);
                storeToComponents();
                conceptsTable.getColumnModel().getColumn(0).setCellRenderer(new CellRenderer(conceptComponents,labelComponents));
                conceptsTable.getColumnModel().getColumn(1).setCellRenderer(new CellRenderer(conceptComponents,labelComponents));
                //getData(ConstList.get(0));
                
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SAXException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            }
        
        } else {
            System.out.println("File access cancelled by user.");
        }
    }
    
    private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuActionPerformed
        System.exit(0);
    }
    private void conceptsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conceptsTableMouseClicked
        //System.out.println("TABLE SELECTED: " + conceptsTable.getSelectedRow());
        //System.out.println("CONTENT: " + conceptsTable.getValueAt(conceptsTable.getSelectedRow(), 0));
        String row, col;
        row = conceptsTable.getValueAt(conceptsTable.getSelectedRow(), 0).toString();
        col = conceptsTable.getValueAt(conceptsTable.getSelectedRow(), 1).toString();
        willPrint = true;
        structure = " ";
        print(ConstList.get(0),row,col);
        //System.out.println("\n\n\n clicked" + structure);
        structureArea.setText(structure);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    	resultArea.setText("One day a girl named Melissa was sitting outside her house. " +
        		"But Melissa was not happy because her eyes were very sore. ");
    	
    	XML xml = new XML("XML Examples\\infected eye generated.xml");
        SAXhandler handler = new SAXhandler();
        xml.setHandler(handler);
        
            try {
                xml.read();
                ConstList = handler.getConstList();
                DefaultTableModel model = new DefaultTableModel();
                conceptsTable.setModel(model);
                model.addColumn("Concept");
                model.addColumn("Label");
                addConceptsToList(ConstList.get(0),model);
                storeToComponents();
                conceptsTable.getColumnModel().getColumn(0).setCellRenderer(new CellRenderer(conceptComponents,labelComponents));
                conceptsTable.getColumnModel().getColumn(1).setCellRenderer(new CellRenderer(conceptComponents,labelComponents));
                //getData(ConstList.get(0));
                
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SAXException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
    
    public void saveFile(){
		JFileChooser fc = new JFileChooser();
		switch (fc.showSaveDialog(this)){
		case JFileChooser.APPROVE_OPTION:
			boolean doExport = true;
		    boolean overrideFile = false;
		    File destinationFile = new File(fc.getSelectedFile().getAbsolutePath());
		    while (doExport && destinationFile.exists() && !overrideFile) {
		        overrideFile = (JOptionPane.showConfirmDialog(this, "Replace file?", 
		        						"Save As", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
		        if (!overrideFile) {
		            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
		                destinationFile = new File(fc.getSelectedFile().getAbsolutePath());
		            else 
		            	doExport = false;
		      
		        }
		    }
		    if (doExport) {
			    	Exporter xmlExporter = new Exporter(ConstList, fc.getSelectedFile().toString());
					xmlExporter.export();
			    
		    }
		break;
		case JFileChooser.CANCEL_OPTION:
            JOptionPane.showMessageDialog(this, "Saving Canceled",
                                          "Semantic Representation",
                                          JOptionPane.OK_OPTION);
        break;
		}
		
	}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Interface().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable conceptsTable;
    private javax.swing.JCheckBoxMenuItem exitMenu;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuItem openMenu;
    private javax.swing.JTextArea resultArea;
    private javax.swing.JTextArea structureArea;
    // End of variables declaration//GEN-END:variables
}
